package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.hst.ThreeDesUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: refresh_token* @Description:系统API接口-- 微软邮箱 通过code获取认证token
 * @author: chieh* @date 2024-02-01 18:00:55
 *
 */

public class apiSync_refresh_token implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSync_refresh_token.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String callBody = "";
        JSONObject outData = new JSONObject();
        outData.put("code", 1);
        outData.put("message", "获取token-令牌刷新操作成功");
        String getMethod = request.getMethod();
        log.debug("apiMiniPControl getMethod:" + getMethod);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("apiMiniPControl Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParams = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("apiMiniPControl Parameter-" + key + ":" + value);
            mapParams.put(key, value);

        }
        log.debug("***原始GET请求参数:" + mapParams.toString());

        String hst_guid = "";
        String ipserver = "";
        //策略待补充，目前固定走 chieh1@dev-cc.kuangheng.com
        //hst_guid="E0069D01-794C-11EE-B1F7-00163E145047";
        hst_guid = mapParams.get("hst_guid");

        /*
        String client_id="d005a907-a74c-43e7-abfa-353198939190";
        String client_secret="HyC8Q~VYik7X-r5-59ktb-yUoVaFuTCbY5mnuaZp";
        String tenan_ID="62508139-839f-43ea-b21f-2da650c20e46";
        String redirect_uri="https://dev-cc.kuangheng.com/ngsapitask_ph/api/apiSync";
         */
        String client_id = "";
        String client_secret = "";
        String tenan_ID = "";
        String grant_type = "refresh_token";
        String refresh_token_befor = "";
        String token_url = "";

        try {

            def gettokencount = eliteBean.chaxun_sql("SELECT hst_guid,ipserver,refresh_token from  hst_email_config where 1=1 and now()>DATE_ADD(expires_Date, INTERVAL expires_in-120 SECOND) ", "dataSource");
            log.debug("SQL获取数据:" + gettokencount);

            for (int i = 0; i < gettokencount.size(); i++) {
                hst_guid = gettokencount.get(i).get("hst_guid");
                ipserver = gettokencount.get(i).get("ipserver");
                refresh_token_befor = gettokencount.get(i).get("refresh_token");
                log.debug("hst_guid:" + hst_guid + "ipserver:" + ipserver+ "refresh_token:" + refresh_token_befor);

                def getSelectSQL = eliteBean.chaxun_sql("select tenan_ID,client_id,client_secret,token_url from hst_email_parameter where 1=1 and hst_guid='" + ipserver + "' order by  updateDate desc limit 1", "dataSource");
                log.debug("SQL获取数据:" + getSelectSQL);

                if (getSelectSQL.size() > 0) {
                    client_id = getSelectSQL.get(0).get("client_id");
                    client_secret = getSelectSQL.get(0).get("client_secret");
                    tenan_ID = getSelectSQL.get(0).get("tenan_ID");
                    //refresh_token_befor = getSelectSQL.get(0).get("refresh_token");
                    token_url = getSelectSQL.get(0).get("token_url");

                    log.debug("client_id:" + client_id + "client_secret:" + client_secret + "tenan_ID:" + tenan_ID + "token_url:" + token_url);
                }

                //String doURL = token_url.replace("{tenant_id}", tenan_ID);
                token_url="https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token";
                String doURL = token_url.replace("{tenant_id}", tenan_ID);
                log.debug("doURL:" + doURL);

                HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                    {
                        put("client_id", client_id);
                        put("client_secret", client_secret);
                        put("grant_type", grant_type);
                        put("refresh_token", refresh_token_befor);
                    }
                };

                String injson = ThreeDesUtil.SplicingMap(paramHashMap, "&");
                log.debug("injson:" + injson);

                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/x-www-form-urlencoded");
                def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
                log.debug("返回的参数getResult:" + getResult);

                //解析SSO返回信息
                JSONObject jsonObject = new JSONObject(getResult);
                String error_codes = GetJV(jsonObject, "error_codes");
                String access_token = GetJV(jsonObject, "access_token");
                String refresh_token = GetJV(jsonObject, "refresh_token");
                String expires_in = GetJV(jsonObject, "expires_in");
                log.debug("error_codes:" + error_codes);
                log.debug("access_token:" + access_token);
                log.debug("refresh_token:" + refresh_token);
                log.debug("expires_in:" + expires_in);

                if (error_codes == "") {
                    //返回认证信息成功
                    def updatetoken = eliteBean.update("update hst_email_config set refresh_token='" + refresh_token + "',access_token='" + access_token + "',expires_in='" + expires_in + "',expires_Date=now() where  hst_guid='" + hst_guid + "'", "dataSource");
                    log.debug("updatetoken:" + updatetoken);
                    //outData.put("access_token", access_token);
                }

            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData.toString();
        }

        log.debug("Esop刷新令牌apiSync_refresh_token返回:" + outData.toString());
        return outData.toString();

    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}